from sqlalchemy.orm import Session
from app.models.setting import SystemSetting, UserSetting
from app.schemas.setting import SystemSettingCreate, SystemSettingUpdate, UserSettingCreate, UserSettingUpdate
from typing import List, Optional, Dict, Any
import json

# === 系统设置CRUD ===

def get_system_setting(db: Session, setting_id: int):
    return db.query(SystemSetting).filter(SystemSetting.id == setting_id).first()

def get_system_setting_by_key(db: Session, key: str):
    return db.query(SystemSetting).filter(SystemSetting.key == key).first()

def get_system_settings(db: Session, category: Optional[str] = None):
    query = db.query(SystemSetting).filter(SystemSetting.is_active == True)
    if category:
        query = query.filter(SystemSetting.category == category)
    return query.all()

def create_system_setting(db: Session, setting: SystemSettingCreate):
    db_setting = SystemSetting(
        category=setting.category,
        key=setting.key,
        value=setting.value,
        data_type=setting.data_type,
        description=setting.description
    )
    db.add(db_setting)
    db.commit()
    db.refresh(db_setting)
    return db_setting

def update_system_setting(db: Session, setting_id: int, setting: SystemSettingUpdate):
    db_setting = db.query(SystemSetting).filter(SystemSetting.id == setting_id).first()
    if db_setting:
        if setting.value is not None:
            db_setting.value = setting.value
        if setting.description is not None:
            db_setting.description = setting.description
        if setting.is_active is not None:
            db_setting.is_active = setting.is_active
        db.commit()
        db.refresh(db_setting)
    return db_setting

def update_system_setting_by_key(db: Session, key: str, value: str):
    db_setting = db.query(SystemSetting).filter(SystemSetting.key == key).first()
    if db_setting:
        db_setting.value = value
        db.commit()
        db.refresh(db_setting)
    else:
        # 如果设置不存在，创建新的设置
        category = key.split('_')[0] if '_' in key else 'system'
        db_setting = SystemSetting(
            category=category,
            key=key,
            value=value,
            data_type="string"
        )
        db.add(db_setting)
        db.commit()
        db.refresh(db_setting)
    return db_setting

# === 用户设置CRUD ===

def get_user_settings(db: Session, user_id: int, category: Optional[str] = None):
    query = db.query(UserSetting).filter(UserSetting.user_id == user_id)
    if category:
        query = query.filter(UserSetting.category == category)
    return query.all()

def get_user_setting_by_category(db: Session, user_id: int, category: str):
    return db.query(UserSetting).filter(
        UserSetting.user_id == user_id,
        UserSetting.category == category
    ).first()

def create_user_setting(db: Session, user_id: int, setting: UserSettingCreate):
    db_setting = UserSetting(
        user_id=user_id,
        category=setting.category,
        settings=setting.settings
    )
    db.add(db_setting)
    db.commit()
    db.refresh(db_setting)
    return db_setting

def update_user_setting(db: Session, user_id: int, category: str, settings: Dict[str, Any]):
    db_setting = db.query(UserSetting).filter(
        UserSetting.user_id == user_id,
        UserSetting.category == category
    ).first()
    
    if db_setting:
        db_setting.settings = settings
        db.commit()
        db.refresh(db_setting)
    else:
        # 如果用户设置不存在，创建新的设置
        db_setting = UserSetting(
            user_id=user_id,
            category=category,
            settings=settings
        )
        db.add(db_setting)
        db.commit()
        db.refresh(db_setting)
    
    return db_setting

# === 工具函数 ===

def get_setting_value(db: Session, key: str, default_value: Any = None):
    """获取设置值，自动转换数据类型"""
    setting = get_system_setting_by_key(db, key)
    if not setting:
        return default_value
    
    try:
        if setting.data_type == "boolean":
            return setting.value.lower() in ('true', '1', 'yes', 'on')
        elif setting.data_type == "integer":
            return int(setting.value)
        elif setting.data_type == "json":
            return json.loads(setting.value)
        else:
            return setting.value
    except (ValueError, json.JSONDecodeError):
        return default_value

def init_default_settings(db: Session):
    """初始化默认系统设置"""
    default_settings = [
        ("system", "system_name", "ITS问题跟踪系统", "string", "系统名称"),
        ("system", "language", "zh-CN", "string", "系统语言"),
        ("system", "timezone", "Asia/Shanghai", "string", "系统时区"),
        ("system", "theme", "light", "string", "系统主题"),
        ("system", "page_size", "20", "integer", "默认分页大小"),
        
        ("security", "session_timeout", "30", "integer", "会话超时时间（分钟）"),
        ("security", "password_min_length", "6", "integer", "密码最小长度"),
        ("security", "login_attempt_limit", "5", "integer", "登录尝试次数限制"),
        ("security", "enable_two_factor", "false", "boolean", "启用双因素认证"),
        
        ("notification", "email_notification", "true", "boolean", "启用邮件通知"),
        ("notification", "system_notification", "true", "boolean", "启用系统通知"),
        ("notification", "issue_assigned", "true", "boolean", "问题分配通知"),
        ("notification", "issue_status_changed", "true", "boolean", "问题状态变更通知"),
        ("notification", "case_updated", "false", "boolean", "案例更新通知"),
    ]
    
    for category, key, value, data_type, description in default_settings:
        existing = get_system_setting_by_key(db, key)
        if not existing:
            setting = SystemSettingCreate(
                category=category,
                key=key,
                value=value,
                data_type=data_type,
                description=description
            )
            create_system_setting(db, setting)